package com.cheetah.start.module.system.controller;

import com.cheetah.start.common.annotation.Log;
import com.cheetah.start.common.base.result.Result;
import com.cheetah.start.common.base.result.ResultController;
import com.cheetah.start.common.enums.BusinessTypeEnum;
import com.cheetah.start.common.enums.LogTypeEnum;
import com.cheetah.start.common.utils.FileUtil;
import com.cheetah.start.module.system.domain.SysFile;
import com.cheetah.start.module.system.service.IUploadService;
import com.cheetah.start.module.system.service.impl.CommonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.Pattern;
import java.io.IOException;

/**
 * 通用
 *
 * @author xjhmwj
 * @date 2021/6/11 17:24
 */
@Api(tags = "通用上传")
@Slf4j
@Validated
@RestController
@RequestMapping("/system/common")
public class CommonController extends ResultController {

    @Autowired
    private CommonService commonService;
    @Autowired
    private IUploadService uploadLocalServiceImpl;
    @Autowired
    private IUploadService uploadAliOssServiceImpl;

    /**
     * 本地上传
     *
     * @param file 文件
     * @return {@link Result}
     */
    @Log(title = "上传", describe = "本地上传", type = BusinessTypeEnum.ADD, logType = LogTypeEnum.OPERATE)
    @ApiOperation(value = "本地上传")
    @PostMapping("/upload")
    public Result upload(MultipartFile file, @Length(max = 20,message = "模块名最大{max}字") @Pattern(regexp = "^[a-zA-Z0-9]+$", message = "模块名只允许英文数字") String moduleName) throws IOException {
        FileUtil.checkCommonSuffix(file);
        SysFile sysFile = uploadLocalServiceImpl.upload(file, moduleName);
        commonService.asyncRecord(sysFile);
        return success(commonService.getResultData(sysFile));
    }


    /**
     * 上传阿里 oss
     *
     * @param file 文件
     * @return {@link Result}
     */
    @Log(title = "上传", describe = "阿里oss上传", type = BusinessTypeEnum.ADD, logType = LogTypeEnum.OPERATE)
    @ApiOperation(value = "阿里云 oss 上传")
    @PostMapping("/upload/ossAliYun")
    public Result uploadAliOss(MultipartFile file, @Length(max = 20) @Pattern(regexp = "^[a-zA-Z0-9]+$\n", message = "模块名只允许英文数字") String moduleName) throws IOException {
        FileUtil.checkCommonSuffix(file);
        SysFile sysFile = uploadAliOssServiceImpl.upload(file, moduleName);
        commonService.asyncRecord(sysFile);
        return success(commonService.getResultData(sysFile));
    }


}
